import { extend, Loading, Notify, Platform } from "quasar";
import { watch } from "vue";
import { parseCookie } from "./utils";

function windowHandle() {
  return {
    async show() {
      Loading.show();
      const win = await window.electron.create(this.name, this.options);
      Loading.hide();
      return win.show();
    },
  };
}

export const updatePage = {
  name: "update",
  /** @type {BrowserWindowOptions} */
  options: {
    icon: "",
    width: 800,
    height: 500,
    useContentSize: true,
    movable: true,
    show: false,
    extendOption: {
      url: "/page/update",
      devtools: true,
    },
  },
  ...windowHandle.apply(this),
};

export const mainWindow = {
  name: "main",
  /** @type {BrowserWindowOptions} */
  options: {
    icon: "",
    width: 1400,
    height: 800,
    minWidth: 1260,
    minHeight: 760,
    useContentSize: true,
    movable: true,
    show: true,
    webPreferences: {
      webviewTag: true,
      nodeIntegration: true,
      contextIsolation: true,
      preload: true,
    },
    extendOption: {
      url: "/demand-list",
      devtools: true,
    },
  },
  ...windowHandle.apply(this),
};

export const zbjLoginWindow = {
  name: "zbjLogin",
  /** @type {BrowserWindowOptions} */
  options: {
    width: 380,
    height: 580,
    resizable: false,
    minimizable: false,
    maximizable: false,
    fullscreen: false,
    title: "登录账号",
    titleBarStyle: "default",
    show: false,
    webPreferences: {
      contextIsolation: true,
      nodeIntegration: true,
      preload: "目前这里统一用的electron-preload.js",
    },
    extendOption: {
      url: "https://account.zbj.com/login?lgtype=1",
      css: "/electron/into/login-page.css",
      js: "/electron/into/login-page.js",
      form: true,
      cookie: false,
      reload: true,
      // devtools: true,
    },
  },
  ...windowHandle.apply(this),
};

export const settingsWindow = {
  name: "settings",
  /** @type {BrowserWindowOptions} */
  options: {
    width: 480,
    height: 480,
    resizable: false,
    minimizable: false,
    maximizable: false,
    fullscreen: false,
    title: "设置",
    show: false,
    extendOption: {
      url: "/page/settings",
      reload: true,
    },
  },
  ...windowHandle.apply(this),
};

export const authWindow = {
  name: "auth",
  /** @type {BrowserWindowOptions} */
  options: {
    width: 480,
    height: 480,
    show: false,
    extendOption: {
      url: "/page/login",
      // devtools: true,
      reload: true,
    },
  },
  ...windowHandle.apply(this),
};

export const IM = {
  /**
   *
   * @param {CookieType} cookie
   */
  login(cookie) {
    if (!window.electron) {
      return;
    }
    /** @type {BrowserViewOptions} */
    const options = {
      webPreferences: {
        contextIsolation: true,
        nodeIntegration: true,
        preload: "目前这里统一用的electron-preload.js",
        partition: `persist:zbj_${cookie.userid}`,
      },
      extendOption: {
        url: "https://supeicommunicate.zbj.com/seller",
        cookie,
        css: "/electron/into/server-im.css",
        js: "/electron/into/server-im.js",
      },
    };
    window.electron.view.create(cookie.userid, options);
  },
  test(cookie) {
    if (!window.electron) {
      return;
    }
    console.log("sssss");
    /** @type {BrowserViewOptions} */
    const options = {
      width: 800,
      height: 800,
      webPreferences: {
        contextIsolation: true,
        nodeIntegration: true,
        partition: `persist:zbj_${cookie.userid}`,
      },
      extendOption: {
        url: "https://jdyboss.zbj.com/?supei=1",
        cookie,
      },
    };
    window.electron.create("test_" + cookie.userid, options);
  },
};

const trayMenu = [
  {
    id: "settings",
    label: "设置",
  },
  {
    id: "update",
    label: "检查更新",
  },
  // 代码在开发模式下运行或 --debug 的生产模式
  ...(process.env.DEBUGGING
    ? [
        {
          id: "openDevTools",
          label: "打开开发者工具",
        },
      ]
    : []),
  {
    label: "退出",
    role: "quit",
  },
];

const commonOptions = {
  movable: true,
  center: true,
  resizable: false,
  minimizable: false,
  maximizable: false,
  fullscreen: false,
  fullscreenable: false,
  ...(Platform.is.mac
    ? {
        titleBarStyle: "hidden",
        vibrancy: "sidebar",
      }
    : {}),
};

/** @type {Record<WindowName, BrowserWindowOptions>} */
const preloadWindowOptions = {
  settings: {
    width: 480,
    height: 480,
    extendOption: {
      url: "/settings",
      // devtools: true,
    },
  },
  auth: {
    width: 480,
    height: 480,
    show: false,
    extendOption: {
      url: "/login",
      devtools: true,
    },
  },
  accountLogin: {
    width: 380,
    height: 580,
    title: "登录账号",
    titleBarStyle: "default",
    extendOption: {
      url: "https://account.zbj.com/login?lgtype=1",
      css: "/electron/into/login-page.css",
      js: "/electron/into/login-page.js",
      // devtools: true,
      form: true,
      preload: true,
      cookie: false,
    },
  },
};

export function initElectron({ router, store }) {
  ipcRenderer.invoke("isMain").then((is) => {
    if (is) {
      // 设置系统托盘
      ipcRenderer.invoke("setTray", null, trayMenu);
      // 预加载窗口

      for (const name in preloadWindowOptions) {
        if (Object.hasOwnProperty.call(preloadWindowOptions, name)) {
          ipcRenderer.invoke(
            "preloadWindow",
            name,
            extend(true, {}, commonOptions, preloadWindowOptions[name])
          );
        }
      }

      ipcRenderer.on("totalUnreadCount", (event, data) => {
        store.commit("common/setServerMessageCount", data);
      });

      function onAppActivate() {
        if (store.state.persisted.auth.token) {
          ipcRenderer.invoke("operateMainWindow", "show");
        } else {
          launchAuthWindow();
        }
      }
      onAppActivate();
      ipcRenderer.on("appActivate", onAppActivate);

      watch(
        () => store.getters["persisted/accounts"],
        async (val) => {
          val.forEach((v) => {
            const cookie = parseCookie(v.cookie).data;
            chatWiew.preload(cookie);
          });
        },
        {
          immediate: true,
        }
      );
    }
  });

  if (!window.electron) {
    return;
  }
  window.electron.init({ router });

  watch(
    () => store.getters["persisted/accounts"],
    async (val) => {
      const cookies = val.map((v) => parseCookie(v.cookie).data);
      window.electron.setAccount(cookies);
    },
    {
      immediate: true,
    }
  );

  window.electron.setTray(null, menu);
  // TODO 创建系统菜单后页面无法使用ctrl+c|v等快捷操作 冲突问题
  // window.electron.setSystemMenu(menu);

  window.addEventListener("message", function (e) {
    if (!e.data || !e.data.channel) {
      return;
    }
    switch (e.data.channel) {
      // 客服未读消息数量
      case "server-message-count":
        store.commit("common/setServerMessageCount", e.data.data);
        break;
      case "on-click-menu":
        switch (e.data.data.id) {
          case "openDevTools":
            window.electron.openDevTools();
            break;
          case "settings":
            window.electron.openWindow(
              "/settings",
              {
                title: "设置",
                width: 600,
                height: 300,
                x: 600,
                y: 100,
                resizable: false,
                minimizable: false,
                maximizable: false,
                fullscreen: false,
                fullscreenable: false,
              },
              0
            );
            break;
          case "update":
            window.electron.openWindow("/update", {
              title: "更新",
              width: 600,
              height: 200,
              resizable: false,
              minimizable: false,
              maximizable: false,
              fullscreen: false,
              fullscreenable: false,
            });
            break;
        }
        break;
    }
  });
}

/**
 * @type {{
 * [userid: number]:{show:(bounds:Electron.Rectangle,path?:string)=>void},
 * preload:(cookie:CookieType)=>xhr
 * }}
 */
export const chatWiew = {
  url: "https://supeicommunicate.zbj.com/seller",
  preload(cookie) {
    const that = this;
    const name = `chat_${cookie.userid}`;
    const xhr = {
      /** @type {(bounds:Electron.Rectangle,path?:string)=>void} */
      show(bounds, path) {
        console.log("show view:", name);
        const url = path ? that.url + path : null;
        ipcRenderer.invoke("operateView", name, "show", bounds, url);
      },
    };
    this[cookie.userid] = xhr;

    /** @type {BrowserViewOptions} */
    const options = {
      webPreferences: {
        partition: `persist:${name}`,
      },
      extendOption: {
        routePath: "/server",
        url: this.url,
        cookie,
        css: "/electron/into/server-im.css",
        js: "/electron/into/server-im.js",
        preload: true,
        // devtools: true,
      },
    };

    ipcRenderer.invoke("preloadView", name, options);
  },
  // chat: {
  //   url: "https://supeicommunicate.zbj.com/seller",
  //   getName: (str) => `chat_${str}`,
  //   show(userid, bounds, path) {
  //     const name = this.getName(userid);
  //     const url = path ? this.url + path : null;
  //     ipcRenderer.invoke("operateView", name, "show", bounds, url);
  //   },
  // },
};

export function launchAuthWindow(url) {
  ipcRenderer.invoke("isMain").then((is) => {
    if (is) {
      ipcRenderer.invoke("operateMainWindow", "hide");
      openWindow("auth", url);
    }
  });
}

export function openWindow(name, url) {
  ipcRenderer.invoke("openWindow", name, url);
}
